package com.crop.back.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crop.back.common.enums.Deleted;
import com.crop.back.common.enums.RoleEnum;
import com.crop.back.common.utils.ResultBean;
import com.crop.back.common.utils.UserHolder;
import com.crop.back.dto.ProductCategoryDTO;
import com.crop.back.dto.ProductRecordDTO;
import com.crop.back.entity.Product;
import com.crop.back.entity.ProductCategory;
import com.crop.back.entity.ProductRecord;
import com.crop.back.entity.Supplier;
import com.crop.back.service.ProductRecordService;
import com.crop.back.service.ProductService;
import com.crop.back.service.SupplierService;
import static java.util.stream.Collectors.toMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;

/**
 * <p>
 * 生产记录表 前端控制器
 * </p>
 *
 * @author 作者
 * @since 2025-01-20
 */
@RestController
@RequestMapping("/product-record")
public class ProductRecordController {

    @Resource
    private ProductService productService;
    @Resource
    private ProductRecordService recordService;

    @PostMapping("/list")
    public ResultBean getAll(@RequestBody ProductRecordDTO recordDTO) {
        Integer page = recordDTO.getPage();
        Integer pageSize = recordDTO.getPageSize();
        Page<ProductRecord> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<ProductRecord> queryWrapper = new LambdaQueryWrapper<ProductRecord>();
        if(UserHolder.getUser().getRoleId() != RoleEnum.ADMIN.getCode()){
            List<Long> productIdList = productService.getProductIdsBySupplierId(UserHolder.getUser().getReferenceId());
            queryWrapper.in(ProductRecord::getProductId, productIdList);
        }
        queryWrapper.eq(ProductRecord::getDeleted, Deleted.NOT_DELETED.getCode());
        Page<ProductRecord> pageRes = recordService.page(pageInfo, queryWrapper);

        Map<Long, String> map = productService.list(new LambdaQueryWrapper<Product>()
                        .eq(Product::getDeleted, Deleted.NOT_DELETED.getCode()))
                .stream()
                .collect(toMap(
                        Product::getId,
                        Product::getName));

        List<ProductRecordDTO> res = pageRes.getRecords()
                .stream()
                .map(item -> {
                    ProductRecordDTO dto = BeanUtil.copyProperties(item, ProductRecordDTO.class);
                    dto.setProductName(map.getOrDefault(dto.getProductId(), "暂无"));
                    return dto;
                }).collect(Collectors.toList());
        return ResultBean.ok(res, pageRes.getTotal());
    }

    @PostMapping("/get")
    public ResultBean getByCondition(@RequestBody ProductRecordDTO recordDTO) {
        Integer page = recordDTO.getPage();
        Integer pageSize = recordDTO.getPageSize();
        Page<ProductRecord> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<ProductRecord> queryWrapper = new LambdaQueryWrapper<>();
        List<Long> productIds = productService.getProductIdsBySupplierId(UserHolder.getUser().getReferenceId());
        queryWrapper.eq(ProductRecord::getDeleted, Deleted.NOT_DELETED.getCode());
        List<Long> productIdList = productService.list(new LambdaQueryWrapper<Product>()
                        .eq(Product::getDeleted, Deleted.NOT_DELETED.getCode())
                        .like(recordDTO.getProductName() != null, Product::getName, recordDTO.getProductName()))
                .stream()
                .map(Product::getId)
                .toList();
        if (recordDTO.getProductName() != null && productIdList.isEmpty()) {
            return ResultBean.ok();
        }
        if (!productIdList.isEmpty()) {
            queryWrapper.in(ProductRecord::getProductId, productIdList);
        }
        queryWrapper.le(recordDTO.getHighestTemperature() != null, ProductRecord::getTemperature, recordDTO.getHighestTemperature());
        queryWrapper.ge(recordDTO.getLowestTemperature() != null, ProductRecord::getTemperature, recordDTO.getLowestTemperature());
        queryWrapper.like(recordDTO.getGrowthStatus() != null, ProductRecord::getGrowthStatus, recordDTO.getGrowthStatus());
        queryWrapper.in(ProductRecord::getProductId, productIds);
        Page<ProductRecord> pageRes = recordService.page(pageInfo, queryWrapper);

        Map<Long, String> map = productService.list(new LambdaQueryWrapper<Product>()
                        .eq(Product::getDeleted, Deleted.NOT_DELETED.getCode()))
                .stream()
                .collect(toMap(
                        Product::getId,
                        Product::getName));

        List<ProductRecordDTO> res = pageRes.getRecords()
                .stream()
                .map(item -> {
                    ProductRecordDTO dto = BeanUtil.copyProperties(item, ProductRecordDTO.class);
                    dto.setProductName(map.getOrDefault(dto.getProductId(), "暂无"));
                    return dto;
                }).collect(Collectors.toList());
        return ResultBean.ok(res, pageRes.getTotal());
    }

    @PostMapping("/save")
    public ResultBean addOrUpdate(@RequestBody ProductRecordDTO recordDTO) {
        try {
            ProductRecord record = BeanUtil.copyProperties(recordDTO, ProductRecord.class);
            if (recordDTO.getId() == null) {
                recordService.save(record);
                return ResultBean.ok("添加成功");
            } else {
                recordService.updateById(record);
                return ResultBean.ok("修改成功");
            }
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry") || e.getCause().getMessage().contains("Duplicate entry")) {
                return ResultBean.fail("类别名已存在，请检查重复项");
            }
            return ResultBean.fail("保存失败");
        }

    }

    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id) {
        try {
            LambdaUpdateWrapper<ProductRecord> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductRecord::getId, id);
            updateWrapper.set(ProductRecord::getDeleted, Deleted.DELETED.getCode());
            recordService.update(updateWrapper);
            return ResultBean.ok();
        } catch (Exception e) {
            return ResultBean.fail("删除失败");
        }
    }

}
